"""
混合解决方案：
1. 生成高质量的合成图像
2. 同时生成Photoshop脚本，用于在PS中重建图层
3. 提供最佳的工作流程
"""

import os
import uuid
import json
import requests
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from pathlib import Path
from datetime import datetime
from config import Config

class HybridSolution:
    """
    混合解决方案：
    - 生成高质量合成图像
    - 生成Photoshop脚本用于重建图层
    - 保留完整的配置信息
    """
    
    def __init__(self):
        self.export_folder = Config.EXPORT_FOLDER
        self.upload_folder = Config.UPLOAD_FOLDER
    
    def create_hybrid_export(self, template, regions, customization_data, export_format='tif'):
        """
        创建混合导出：
        1. 高质量合成图像
        2. Photoshop重建脚本
        3. JSON配置文件
        """
        print("=== 混合解决方案导出 ===")
        
        # 1. 处理原始文件
        original_image = None
        canvas_width = template['width']
        canvas_height = template['height']
        original_layers_info = []
        
        if template.get('image_path'):
            image_path = template['image_path']
            template_image_path = Path(image_path) if Path(image_path).is_absolute() else self.upload_folder / image_path
            
            if template_image_path.exists():
                print(f"加载原始文件: {template_image_path}")
                
                if template_image_path.suffix.lower() == '.psd':
                    # PSD文件处理
                    try:
                        from psd_tools import PSDImage
                        psd = PSDImage.open(template_image_path)
                        original_image = psd.composite()
                        canvas_width, canvas_height = psd.width, psd.height
                        
                        # 提取图层信息用于脚本生成
                        original_layers_info = self._extract_psd_layers_info(psd)
                        print(f"PSD图层数: {len(original_layers_info)}")
                        
                    except ImportError:
                        print("警告：psd-tools未安装")
                    except Exception as e:
                        print(f"PSD处理失败: {e}")
                else:
                    # 其他格式
                    original_image = Image.open(template_image_path)
                    canvas_width, canvas_height = original_image.size
        
        if not original_image:
            original_image = Image.new('RGBA', (canvas_width, canvas_height), (255, 255, 255, 255))
        
        if original_image.mode != 'RGBA':
            original_image = original_image.convert('RGBA')
        
        # 2. 处理JSON图片（使用用户精确位置）
        composite_image = original_image.copy()
        json_elements_info = []
        
        for region_index, region_data in customization_data.get('regions', {}).items():
            elements = region_data.get('elements', [])
            
            for element_idx, element in enumerate(elements):
                element_info = self._process_json_element(
                    composite_image, element, canvas_width, canvas_height
                )
                if element_info:
                    json_elements_info.append(element_info)
        
        # 3. 保存文件
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        unique_id = str(uuid.uuid4())[:8]
        
        # 主图像文件
        if export_format.lower() == 'psd':
            main_filename = f"hybrid_psd_{timestamp}_{unique_id}.tif"
        else:
            main_filename = f"hybrid_{timestamp}_{unique_id}.{export_format}"
        
        main_path = self.export_folder / main_filename
        
        # 保存主图像
        if export_format.lower() in ['jpg', 'jpeg']:
            if composite_image.mode == 'RGBA':
                rgb_image = Image.new('RGB', composite_image.size, (255, 255, 255))
                rgb_image.paste(composite_image, mask=composite_image.split()[-1])
                composite_image = rgb_image
            composite_image.save(main_path, 'JPEG', quality=95)
        else:
            composite_image.save(main_path, 'TIFF', compression='lzw')
        
        # 4. 生成Photoshop脚本
        script_path = self._generate_photoshop_script(
            template, original_layers_info, json_elements_info, 
            main_path, timestamp, unique_id
        )
        
        # 5. 保存配置文件
        config_path = self._save_configuration(
            template, customization_data, timestamp, unique_id
        )
        
        print(f"\\n=== 混合导出完成 ===")
        print(f"主图像: {main_path}")
        print(f"PS脚本: {script_path}")
        print(f"配置文件: {config_path}")
        print(f"文件大小: {main_path.stat().st_size / 1024 / 1024:.2f} MB")
        print(f"原始图层: {len(original_layers_info)}")
        print(f"JSON元素: {len(json_elements_info)}")
        
        return main_path
    
    def _extract_psd_layers_info(self, psd):
        """提取PSD图层信息"""
        layers_info = []
        
        def extract_recursive(container, prefix=""):
            for layer in container:
                layer_info = {
                    'name': f"{prefix}{layer.name}",
                    'type': str(layer.kind),
                    'visible': layer.visible,
                    'opacity': getattr(layer, 'opacity', 255),
                    'blend_mode': str(getattr(layer, 'blend_mode', 'normal')),
                    'is_group': layer.is_group()
                }
                
                if hasattr(layer, 'bbox') and layer.bbox:
                    try:
                        bbox = layer.bbox
                        if hasattr(bbox, 'width'):
                            layer_info['bbox'] = {
                                'x': bbox.x1, 'y': bbox.y1,
                                'width': bbox.width, 'height': bbox.height
                            }
                    except:
                        pass
                
                layers_info.append(layer_info)
                
                if layer.is_group():
                    extract_recursive(layer, f"{layer.name}/")
        
        extract_recursive(psd)
        return layers_info
    
    def _process_json_element(self, composite_image, element, canvas_width, canvas_height):
        """处理JSON元素，返回元素信息"""
        image_url = element.get('image_url')
        if not image_url:
            return None
        
        user_data = element.get('user_placement_data', {})
        
        # 下载图片
        try:
            response = requests.get(image_url, timeout=30)
            response.raise_for_status()
            element_image = Image.open(BytesIO(response.content))
            download_success = True
        except Exception as e:
            print(f"下载失败: {e}")
            # 创建占位符
            element_image = Image.new('RGBA', (200, 200), (255, 0, 0, 255))
            draw = ImageDraw.Draw(element_image)
            draw.rectangle([0, 0, 199, 199], outline=(0, 0, 0, 255), width=3)
            draw.text((50, 90), "下载失败", fill=(255, 255, 255, 255))
            download_success = False
        
        if element_image.mode != 'RGBA':
            element_image = element_image.convert('RGBA')
        
        # 应用用户设置
        dimension = user_data.get('dimension', {})
        if dimension.get('width') and dimension.get('height'):
            new_size = (int(dimension['width']), int(dimension['height']))
            element_image = element_image.resize(new_size, Image.Resampling.LANCZOS)
        
        angle = user_data.get('angle_of_rotation', 0)
        if angle != 0:
            element_image = element_image.rotate(angle, expand=True, fillcolor=(0, 0, 0, 0))
        
        # 使用用户精确位置（不进行边界限制）
        position = user_data.get('position', {})
        x = int(position.get('x', 0))
        y = int(position.get('y', 0))
        
        print(f"JSON元素位置: ({x}, {y}), 尺寸: {element_image.size}")
        
        # 合成到主图像
        try:
            composite_image.paste(element_image, (x, y), element_image)
            print(f"✅ JSON元素合成成功")
        except Exception as e:
            print(f"合成失败: {e}")
        
        # 返回元素信息
        return {
            'url': image_url,
            'position': {'x': x, 'y': y},
            'size': {'width': element_image.width, 'height': element_image.height},
            'rotation': angle,
            'download_success': download_success,
            'user_data': user_data
        }
    
    def _generate_photoshop_script(self, template, original_layers, json_elements, main_path, timestamp, unique_id):
        """生成Photoshop脚本用于重建图层"""
        script_filename = f"photoshop_rebuild_{timestamp}_{unique_id}.jsx"
        script_path = self.export_folder / script_filename
        
        script_content = f'''// Photoshop脚本：重建图层结构
// 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
// 原始文件: {template.get('image_path', 'Unknown')}

// 1. 打开合成图像
var mainFile = new File("{main_path.as_posix()}");
var doc = app.open(mainFile);

// 2. 原始图层信息
// 原始文件包含 {len(original_layers)} 个图层：
{self._format_layers_comment(original_layers)}

// 3. 添加JSON配置的图片作为新图层
'''
        
        for i, element in enumerate(json_elements):
            if element['download_success']:
                script_content += f'''
// JSON图层 {i+1}
try {{
    // 下载并打开图片
    var jsonImageFile = new File("{element['url']}");
    // 注意：需要手动下载图片到本地，然后修改路径
    
    // 创建新图层
    var newLayer = doc.artLayers.add();
    newLayer.name = "JSON图片_{i+1}";
    
    // 设置图层位置和属性
    // 位置: ({element['position']['x']}, {element['position']['y']})
    // 尺寸: {element['size']['width']} x {element['size']['height']}
    // 旋转: {element['rotation']}度
    
    // 手动说明：
    // 1. 下载图片: {element['url']}
    // 2. 在Photoshop中打开并复制
    // 3. 粘贴到主文档作为新图层
    // 4. 移动到位置 ({element['position']['x']}, {element['position']['y']})
    // 5. 调整尺寸为 {element['size']['width']} x {element['size']['height']}
    
}} catch(e) {{
    alert("处理JSON图层 {i+1} 时出错: " + e.message);
}}
'''
        
        script_content += '''
// 脚本完成
alert("图层重建脚本执行完成！\\n请按照注释中的说明手动添加JSON图片。");
'''
        
        with open(script_path, 'w', encoding='utf-8') as f:
            f.write(script_content)
        
        return script_path
    
    def _format_layers_comment(self, layers):
        """格式化图层信息为注释"""
        comment = ""
        for layer in layers:
            indent = "//   " + "  " * layer.get('level', 0)
            icon = "📁" if layer.get('is_group') else "🖼️"
            comment += f"{indent}{icon} {layer['name']} ({layer['type']})\n"
        return comment
    
    def _save_configuration(self, template, customization_data, timestamp, unique_id):
        """保存完整的配置信息"""
        config_filename = f"config_{timestamp}_{unique_id}.json"
        config_path = self.export_folder / config_filename
        
        config_data = {
            'timestamp': timestamp,
            'template': template,
            'customization_data': customization_data,
            'export_info': {
                'canvas_size': {'width': template['width'], 'height': template['height']},
                'elements_count': sum(len(region.get('elements', [])) for region in customization_data.get('regions', {}).values()),
                'instructions': [
                    "此文件包含完整的配置信息",
                    "可用于重新生成或在其他系统中重建",
                    "JSON元素的位置信息完全保留"
                ]
            }
        }
        
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(config_data, f, ensure_ascii=False, indent=2)
        
        return config_path
